package com.guan.friend.controller.user;

import cn.hutool.core.util.StrUtil;
import com.guan.common.core.baseController.BaseController;
import com.guan.common.core.constants.HttpConstants;
import com.guan.common.core.domain.R;
import com.guan.common.core.domain.VO.LoginUserVO;
import com.guan.friend.domain.user.dto.UserDTO;
import com.guan.friend.domain.user.dto.UserDetailUpdateDTO;
import com.guan.friend.domain.user.vo.UserVO;
import com.guan.friend.service.user.IUserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;

    @PostMapping("/sendCode")
    public R<Void> sendCode(@RequestBody UserDTO userDTO){
        return toR(userService.sendCode(userDTO));
    }

    @PostMapping("/code/login")
    public R<String> codeLogin(@RequestBody UserDTO userDTO){
        return R.ok(userService.codeLogin(userDTO.getPhone(), userDTO.getCode()));
    }

    @DeleteMapping("/logout")
    public R<Void> logout(HttpServletRequest request){
        // 处理 得到有效 token
        String token = request.getHeader(HttpConstants.AUTHENTICATION);
        if(StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)){
            token = token.replaceFirst(HttpConstants.PREFIX, "");
        }
        //System.out.println(token);

        return toR(userService.logout(token));
    }

    @GetMapping("/info")
    public R<LoginUserVO> info(@RequestHeader(HttpConstants.AUTHENTICATION) String token){
        LoginUserVO loginUserVO = userService.info(token);
        if (loginUserVO == null) return R.fail();
        return R.ok(loginUserVO);
    }

    @GetMapping("/detail")
    public R<UserVO> detail(){
        return R.ok(userService.detail());
    }

    @PutMapping("/edit")
    public R<Integer> edit(@RequestBody UserDetailUpdateDTO userDetailDTO){
        return R.ok(userService.edit(userDetailDTO));
    }

    @PutMapping("/head-image/update")
    public R<Void> updateHeadImage(@RequestBody UserDetailUpdateDTO userDetailUpdateDTO ){
        return toR(userService.updateHeadImage(userDetailUpdateDTO));
    }

}
